(function(jQuery) {
	jQuery.fn.reset = function() {
		var f = jQuery(this), find = function(selector) {
			return f.is("form") ? f.find(selector) : f.find(selector);
		};
		find("input:text,input:hidden,input:password,textarea").each(
				function() {
					var $input = jQuery(this);
					$input.val("");
				});
		find("select").each(function() {
			var $input = jQuery(this);
			$input.find("option").each(function() {
				this.selected = false;
			});
			if ($input.hasClass("chosen-select")) {
				$input.chosen('destroy');
				$input.chosen(chosenConfig['.chosen-select']);
				$input.trigger("chosen:updated");
			}
			var dataLinkId = $input.attr("data-linkId");
			if (dataLinkId) {
				var dataLinkIdOpt = $(dataLinkId + " option:first");
				$(dataLinkId).empty();
				$(dataLinkId).append(dataLinkIdOpt);
			}
		});
		find("input:checkbox,input:radio").each(function() {
			var $input = jQuery(this);
			$input.iCheck("uncheck");
			// this.checked = false;
		})
		return this;
	};

	jQuery.fn.serializeObject = function() {
		var f = jQuery(this);
		var result = {};
		find = function(selector) {
			return f.find(selector);
		};
		build = function(key, value, isArr) {
			if (isArr) {
				if (result[key]) {
					var obj = result[key];
					obj.push(value);
					result[key] = obj;
				} else {
					var array = new Array();
					array.push(value);
					result[key] = array;
				}
			} else {
				result[key] = value;
			}
		};
		find(":input")
				.each(
						function() {
							var $input = jQuery(this);
							var name = $input.attr("name");
							if (name == undefined) {
								return;
							}
							if (this.tagName == 'INPUT') {
								var type = $input.attr("type");
								if (type != undefined
										&& (type == 'checkbox' || type == 'radio')) {
									if ($input.is(":checked")) {
										var isArr = $input.attr("multiple") != undefined;
										build(name, $input.attr("data-value"),
												isArr);
									}
								} else {
									var isArr = $input.attr("multiple") != undefined;
									build(name, $input.val(), isArr);
								}
							} else if (this.tagName == 'TEXTAREA') {
								build(name, $input.val());
							} else if (this.tag = "SELECT") {
								var multiple = $input.attr("multiple") != undefined;
								if (multiple) {
									var values = new Array();
									$input.find("option").each(function() {
										if (this.selected) {
											values.push(this.value);
										}
									});
									build(name, values);
								} else {
									$input.find("option").each(function() {
										if (this.selected) {
											build(name, this.value);
										}
									});
								}
							}
						});
		return result;
	};
	jQuery.fn.serializeJSON = function() {
		return JSON.stringify(jQuery(this).serializeObject());
	};
	jQuery.fn.deserialize = function(data) {
		var f = jQuery(this), map = data, find = function(selector) {
			return f.is("form") ? f.find(selector) : f.filter(f.attr("id")
					+ " " + selector);
		};
		find(":input").each(function() {
			var $input = jQuery(this);
			var name = $input.attr("name");
			var value = map[name];
			if (value == undefined) {
				return;
			}
			if (this.tagName == 'INPUT') {
				$input.val(value);
			} else if (this.tag = "SELECT") {
				var values = map[name];
				var multiple = $input.attr("multiple") != undefined;
				$input.find("option").each(function() {
					if (multiple) {
						this.selected = false;
						for (var i = 0; i < values.length; i++) {
							if (values[i] == this.value) {
								this.selected = true;
								break;
							}
						}
					} else {
						this.selected = this.value == values
					}
				});
				$input.trigger("chosen:updated");
			}
		});

	};
})(jQuery);

$(document)
		.ready(
				function() {
					$.fn.datetimepicker.dates['zh-CN'] = {
						days : [ "星期日", "星期一", "星期二", "星期三", "星期四", "星期五",
								"星期六", "星期日" ],
						daysShort : [ "日", "一", "二", "三", "四", "五", "六", "日" ],
						daysMin : [ "日", "一", "二", "三", "四", "五", "六", "日" ],
						months : [ "一月", "二月", "三月", "四月", "五月", "六月", "七月",
								"八月", "九月", "十月", "十一月", "十二月" ],
						monthsShort : [ "一", "二", "三", "四", "五", "六", "七", "八",
								"九", "十", "十一", "十二" ],
						meridiem : [ "上午", "下午" ],
						today : "今天"
					};

					$('.input-daterange .minute-datepicker').datetimepicker({
						startView : 2,
						minView : 0,
						keyboardNavigation : false,
						forceParse : false,
						autoclose : true,
						language : "zh-CN",
						format : "yyyy-mm-dd hh:ii",
						minuteStep : 1
					});

					$('.input-daterange .hour-datepicker').datetimepicker({
						startView : 2,
						minView : 1,
						keyboardNavigation : false,
						forceParse : false,
						autoclose : true,
						language : "zh-CN",
						format : "yyyy-mm-dd hh"
					});

					$('.input-daterange .date-datepicker').datetimepicker({
						startView : 2,
						minView : 2,
						keyboardNavigation : false,
						forceParse : false,
						autoclose : true,
						language : "zh-CN",
						format : "yyyy-mm-dd"
					});

					$('.input-daterange .month-datepicker').datetimepicker({
						startView : 3,
						minView : 3,
						keyboardNavigation : false,
						forceParse : false,
						autoclose : true,
						language : "zh-CN",
						format : "yyyy-mm"
					});

					$('.input-daterange .minuterange-start').datetimepicker({
						startView : 2,
						minView : 0,
						keyboardNavigation : false,
						forceParse : false,
						autoclose : true,
						language : "zh-CN",
						format : "yyyy-mm-dd hh:ii",
						minuteStep : 1
					}).on(
							'changeDate',
							function(e) {
								var startTime = e.date;
								var daterangeEnd = $(this).parent().find(
										"input")[1];
								jQuery(daterangeEnd).datetimepicker(
										'setStartDate', startTime);
							});

					$('.input-daterange .minuterange-end').datetimepicker({
						startView : 2,
						minView : 0,
						keyboardNavigation : false,
						forceParse : false,
						autoclose : true,
						language : "zh-CN",
						format : "yyyy-mm-dd hh:ii",
						minuteStep : 1
					}).on(
							'changeDate',
							function(e) {
								var endTime = e.date;
								var daterangeStart = $(this).parent().find(
										"input")[0];
								jQuery(daterangeStart).datetimepicker(
										'setEndDate', endTime);
							});

					$('.input-daterange .hourrange-start').datetimepicker({
						startView : 2,
						minView : 1,
						keyboardNavigation : false,
						forceParse : false,
						autoclose : true,
						language : "zh-CN",
						format : "yyyy-mm-dd hh"
					}).on(
							'changeDate',
							function(e) {
								var startTime = e.date;
								var daterangeEnd = $(this).parent().find(
										"input")[1];
								jQuery(daterangeEnd).datetimepicker(
										'setStartDate', startTime);
							});

					$('.input-daterange .hourrange-end').datetimepicker({
						startView : 2,
						minView : 1,
						keyboardNavigation : false,
						forceParse : false,
						autoclose : true,
						language : "zh-CN",
						format : "yyyy-mm-dd hh"
					}).on(
							'changeDate',
							function(e) {
								var endTime = e.date;
								var daterangeStart = $(this).parent().find(
										"input")[0];
								jQuery(daterangeStart).datetimepicker(
										'setEndDate', endTime);
							});

					$('.input-daterange .daterange-start').datetimepicker({
						startView : 2,
						minView : 2,
						keyboardNavigation : false,
						forceParse : false,
						autoclose : true,
						language : "zh-CN",
						format : "yyyy-mm-dd"
					}).on(
							'changeDate',
							function(e) {
								var startTime = e.date;
								var daterangeEnd = $(this).parent().find(
										"input")[1];
								jQuery(daterangeEnd).datetimepicker(
										'setStartDate', startTime);
							});

					$('.input-daterange .daterange-end').datetimepicker({
						startView : 2,
						minView : 2,
						keyboardNavigation : false,
						forceParse : false,
						autoclose : true,
						language : "zh-CN",
						format : "yyyy-mm-dd"
					}).on(
							'changeDate',
							function(e) {
								var endTime = e.date;
								var daterangeStart = $(this).parent().find(
										"input")[0];
								jQuery(daterangeStart).datetimepicker(
										'setEndDate', endTime);
							});

					$('.input-daterange .monthrange-start').datetimepicker({
						startView : 3,
						minView : 3,
						keyboardNavigation : false,
						forceParse : false,
						autoclose : true,
						language : "zh-CN",
						format : "yyyy-mm"
					}).on(
							'changeDate',
							function(e) {
								var startTime = e.date;
								var daterangeEnd = $(this).parent().find(
										"input")[1];
								jQuery(daterangeEnd).datetimepicker(
										'setStartDate', startTime);
							});

					$('.input-daterange .monthrange-end').datetimepicker({
						startView : 3,
						minView : 3,
						keyboardNavigation : false,
						forceParse : false,
						autoclose : true,
						language : "zh-CN",
						format : "yyyy-mm"
					}).on(
							'changeDate',
							function(e) {
								var endTime = e.date;
								var daterangeStart = $(this).parent().find(
										"input")[0];
								jQuery(daterangeStart).datetimepicker(
										'setEndDate', endTime);
							});

					$(".chosen-select").each(function() {
						id = $(this).attr("id");
						if (!document.getElementById(id + "_chosen")) {
							$(this).chosen();
						}
					});

					$('.input-daterange .range-start').change(
							function() {
								$(this).datetimepicker('update');
								var daterangeEnd = $(this).parent().find(
										"input")[1];
								jQuery(daterangeEnd).datetimepicker(
										'setStartDate', $(this).val());
							});

					$('.input-daterange .range-end').change(
							function() {
								$(this).datetimepicker('update');
								var daterangeStart = $(this).parent().find(
										"input")[0];
								jQuery(daterangeStart).datetimepicker(
										'setEndDate', $(this).val());
							});

					$('.i-checks').iCheck({
						checkboxClass : 'icheckbox_square-green',
						radioClass : 'iradio_square-green',
					});

					$('.i-tagsinput').tagsInput({
						width : 'auto',
						interactive : false
					});
				})

// TagsInput对象
function TagsInputObject(objId) {
	this.objId = objId;
	this.exist = function(label, value) {
		return $('#' + this.objId).tagExist(this.getTagsKey(label, value));
	};
	this.add = function(label, value, inputName) {
		var name = this.getTagsKey(label, value);
		if (!$('#' + this.objId).tagExist(name)) {
			$('#' + this.objId).addTag(name, null, inputName, value);
		}
	};
	this.remove = function(label, value) {
		var name = this.getTagsKey(label, value);
		if ($('#' + this.objId).tagExist(name)) {
			$('#' + this.objId).removeTag(name);
		}
	};
	this.clear = function() {
		$('#' + this.objId).importTags('');
	}
	this.getTagsKey = function(label, value) {
		return label + "[" + value + "]";
	}
}

function replaceParameter(url, paraName, paraValue) {
	if (paraName == '')
		return url;
	var updateUrl;
	if (url.indexOf(paraName) == -1) {
		if (url.indexOf("?") == -1)
			updateUrl = url + '?' + paraName + '=' + paraValue;
		else
			updateUrl = url + '&' + paraName + '=' + paraValue;
	} else {
		var reg = new RegExp(paraName + "=\\w*", "g");
		updateUrl = url.replace(reg, paraName + "=" + paraValue);
	}
	return updateUrl;
}

/**
 * 输出访问错误
 * 
 * @param message
 * @returns {Function}
 */
function consoleError(message) {
	return function(error) {
		console.log(message + 'error status json:' + JSON.stringify(error));
	}
}

function selectLink(select, id, url, initVal) {
	var dataLinkIdOpt = $(id + " option:first");
	$(id).empty();
	if (($(id).attr("multiple") == undefined))
		$(id).append(dataLinkIdOpt);

	if ($(id).hasClass("chosen-select")) {
		$(id).trigger("chosen:updated");
	}

	if (select.value != '') {
		var dataUrl = url + select.value;
		$.get(dataUrl, function(data) {
			$(data).each(function() {
				var opt = $('<option>', {
					value : this.code
				}).text(this.name);
				$(id).append(opt);
			});
			if (initVal) {
				$(id).val(initVal);
			}
			if ($(id).hasClass("chosen-select")) {
				$(id).trigger("chosen:updated");
			}
		});
	}
}

function loadSelect(id, url, initVal) {
	var dataLinkIdOpt = $(id + " option:first");
	$(id).empty();

	if (($(id).attr("multiple") == undefined))
		$(id).append(dataLinkIdOpt);

	$.get(url, function(data) {
		$(data).each(function() {
			var opt = $('<option>', {
				value : this.code
			}).text(this.name);
			$(id).append(opt);
		});
		if (initVal) {
			$(id).val(initVal);
		}
		if ($(id).hasClass("chosen-select")) {
			$(id).trigger("chosen:updated");
		}
	});
}

Date.prototype.add = function(interval, number) {
	var d = new Date(this.getTime());
	var k = {
		'y' : 'FullYear',
		'q' : 'Month',
		'm' : 'Month',
		'w' : 'Date',
		'd' : 'Date',
		'h' : 'Hours',
		'n' : 'Minutes',
		's' : 'Seconds',
		'ms' : 'MilliSeconds'
	};
	var n = {
		'q' : 3,
		'w' : 7
	};
	eval('d.set' + k[interval] + '(d.get' + k[interval] + '()+'
			+ ((n[interval] || 1) * number) + ')');
	return d;
}

Date.prototype.diff = function(interval, objDate2) {
	var d = this, i = {}, t = d.getTime(), t2 = objDate2.getTime();
	i['y'] = objDate2.getFullYear() - d.getFullYear();
	i['q'] = i['y'] * 4 + Math.floor(objDate2.getMonth() / 4)
			- Math.floor(d.getMonth() / 4);
	i['m'] = i['y'] * 12 + objDate2.getMonth() - d.getMonth();
	i['ms'] = objDate2.getTime() - d.getTime();
	i['w'] = Math.floor((t2 + 345600000) / (604800000))
			- Math.floor((t + 345600000) / (604800000));
	i['d'] = Math.floor(t2 / 86400000) - Math.floor(t / 86400000);
	i['h'] = Math.floor(t2 / 3600000) - Math.floor(t / 3600000);
	i['n'] = Math.floor(t2 / 60000) - Math.floor(t / 60000);
	i['s'] = Math.floor(t2 / 1000) - Math.floor(t / 1000);
	return i[interval];
}
function parsePrice(s) {
	var n = 2;// 设置保留的小数位数
	s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
	var l = s.split(".")[0].split("").reverse();
	var r = s.split(".")[1];
	var t = "";
	for (i = 0; i < l.length; i++) {
		t += l[i];
		if ((i + 1) % 3 == 0 && i > 0 && i < l.length - 1) {
			t += ",";
		}
	}
	return '￥' + t.split("").reverse().join("") + "." + r;
}

Vue.filter('moment', function(value, formatString) {
	if (value) {
		formatString = formatString || 'yyyy-mm-dd HH:mm:ss';
		return moment(value).format(formatString);
	} else {
		return '';
	}
});

Vue.filter('dateDiff', function(beginDate, endDate, formatString) {
	if (beginDate && endDate) {
		formatString = formatString || 'yyyy-mm-dd HH:mm:ss';
		// return moment.utc().format("HH:mm:ss")

		var ms = moment(endDate).diff(moment(beginDate));
		var d = moment.duration(ms);
		return Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
	} else {
		return '';
	}
});

var vueEnumData;
Vue.filter('enums', function(value) {
	return vueEnumData[value];
});

Vue.filter("getFileName", function(value) { // 获取文件名
	return value.split('/').pop() || "";
});

Vue.filter("BYTE2MB", function(value) {
	var fileSize = new Number(value / 1024 / 1024);
	return fileSize.toFixed(2);
});

Vue.filter("KB2GB", function(value) {
	var fileSize = new Number(value / 1024 / 1024);
	return fileSize.toFixed(2);
});

function replace(str, src, dst) {
	return str.replace(src, dst);
}

function mathRand(size) {
	var res = "";
	for (var i = 0; i < size; i++) {
		res += Math.floor(Math.random() * 10);
	}
	return res;
}

function getTop(e) {
	var offset = e.offsetTop;
	while (e.offsetParent != null) {
		e = e.offsetParent;
		if (e.tagName != "A" && e.tagName != "TD" && e.tagName != "TABLE") {
			break;
		}
		offset += e.offsetTop;
	}
	return offset;
}

function getBottom(e) {
	var offset = getTop(e);
	offset += e.offsetHeight;
	return offset;
}

function getLeft(e) {
	var offset = e.offsetLeft;
	while (e.offsetParent != null) {
		e = e.offsetParent;
		if (e.tagName != "A" && e.tagName != "TD" && e.tagName != "TABLE") {
			break;
		}
		offset += e.offsetLeft;
	}
	return offset;
}

function isBelongTop(e) {
	var elementTop = e.getBoundingClientRect().top;
	var windowHeight = $(window).height();
	return parseInt(elementTop) < parseInt(windowHeight) / 2;
}

(function(global) {

	if (typeof (global) === "undefined") {
		throw new Error("window is undefined");
	}

	var _hash = "!";
	var noBackPlease = function() {
		global.location.href += "#";

		// making sure we have the fruit available for juice....
		// 50 milliseconds for just once do not cost much (^__^)
		global.setTimeout(function() {
			global.location.href += "!";
		}, 50);
	};

	// Earlier we had setInerval here....
	global.onhashchange = function() {
		if (global.location.hash !== _hash) {
			global.location.hash = _hash;
		}
	};

	global.onload = function() {

		// noBackPlease();

		// disables backspace on page except on input fields and textarea..
		document.body.onkeydown = function(e) {
			var elm = e.target.nodeName.toLowerCase();
			if (e.which === 8 && (elm !== 'input' && elm !== 'textarea')) {
				e.preventDefault();
			}
			// stopping event bubbling up the DOM tree..
			e.stopPropagation();
		};

	};

})(window);

// 获取滚动条当前的位置
function getScrollTop() {
	var scrollTop = 0;
	if (document.documentElement && document.documentElement.scrollTop) {
		scrollTop = document.documentElement.scrollTop;
	} else if (document.body) {
		scrollTop = document.body.scrollTop;
	}
	return scrollTop;
}

// 获取当前可是范围的高度
function getClientHeight() {
	var clientHeight = 0;
	if (document.body.clientHeight && document.documentElement.clientHeight) {
		clientHeight = Math.min(document.body.clientHeight,
				document.documentElement.clientHeight);
	} else {
		clientHeight = Math.max(document.body.clientHeight,
				document.documentElement.clientHeight);
	}
	return clientHeight;
}

// 获取文档完整的高度
function getScrollHeight() {
	return Math.max(document.body.scrollHeight,
			document.documentElement.scrollHeight);
}

// 是否到底
function isScrollEnd() {
	return getScrollTop() + getClientHeight() == getScrollHeight();
}